//
//  GuidePageViewController.m
//  CreditHub
//
//  Created by chenglang on 2024/9/11.
//

#import "TabbarViewController.h"
#import "PersonalCenterVC.h"
#import "TabbarCollectionViewCell.h"
#import "DKWHomeViewController.h"
#import "OrderViewController.h"
#import "LoginViewController.h"
#import "HomeRequest.h"
#import "CHLocationManager.h"

@interface TabbarViewController ()<UIPageViewControllerDataSource, UIPageViewControllerDelegate,UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, assign) NSInteger selectIndex;
@property (nonatomic, strong) NSArray *arryViewControllers;
@property (strong, nonatomic) UIPageViewController *pageViewController;
@property (nonatomic, strong) NSArray *arrayTabbar;

@end

@implementation TabbarViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[CHLocationManager sharedInstance] checkLocationPermission] ;
    
    self.arrayTabbar = @[@"tabbar_home",@"tabbar_order",@"tabbar_mine"];
    self.selectIndex = 0;
    self.view.backgroundColor = UIColor.whiteColor;
    
    DKWHomeViewController *view1 = [[DKWHomeViewController alloc] init];
    OrderViewController *view2 = [[OrderViewController alloc] init];
    PersonalCenterVC *view3 = [[PersonalCenterVC alloc] init];
    
    self.arryViewControllers = @[view1,view2,view3];
    //    UIPageViewControllerTransitionStyleScroll
    self.pageViewController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];
    self.pageViewController.dataSource = self;
    self.pageViewController.delegate = self;
    [self.pageViewController setViewControllers:@[view1] direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
    
    CGRect rect =self.view.bounds;
    rect.size.height = rect.size.height - 49-SYS_TabBarFloatHeight;
    self.pageViewController.view.frame = rect;
    [self addChildViewController:self.pageViewController];
    [self.view addSubview:self.pageViewController.view];
    [self.pageViewController didMoveToParentViewController:self];
    
    for (UIView *view in self.pageViewController.view.subviews) {
        if([view isKindOfClass:[UIScrollView class]]){
            UIScrollView *scrollview = (UIScrollView *)view;
            scrollview.scrollEnabled = NO;
        }
    }
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumInteritemSpacing = 0;
        layout.minimumLineSpacing = 0;
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT-49-SYS_TabBarFloatHeight, SCREEN_WIDTH, 49+SYS_TabBarFloatHeight+50) collectionViewLayout:layout];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.backgroundColor = UIColor.blackColor;
    self.collectionView.cornerRadius = 30;
    [self.view addSubview:self.collectionView];
    
    
    [self.collectionView registerNib:[UINib nibWithNibName:@"TabbarCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"TabbarCollectionViewCell"];
    
    [self requestCityList];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationHome:) name:NotificationBackHomeKey object:nil];
}

- (void)notificationHome:(NSNotification *)nofication{
    NSInteger index = [nofication.object[@"index"] integerValue];
    if(index<self.arryViewControllers.count){
        
        if( ![UserInfoModel isLogin] ){
            index = 0;
           
        }
    
        self.selectIndex = index;
        [self.collectionView reloadData];
        [self.pageViewController setViewControllers:@[self.arryViewControllers[index]] direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
        
        if( ![UserInfoModel isLogin] && [nofication.object[@"index"] integerValue]!=0 ){
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                LoginViewController *vc = [[LoginViewController alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
            });
            
         
        }else if(index ==1){
            [[NSNotificationCenter defaultCenter] postNotificationName:NotificationOrderKey object:@{@"index":nofication.object[@"type"]}];
        }
        
    }
    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.arrayTabbar.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    TabbarCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TabbarCollectionViewCell" forIndexPath:indexPath];
    cell.imageIcon.image = [UIImage imageNamed:self.arrayTabbar[indexPath.row]];
    cell.lblPoint.hidden = YES;
    if(indexPath.row == self.selectIndex){
        cell.imageIcon.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@_select",self.arrayTabbar[indexPath.row]]];
        cell.lblPoint.hidden = NO;
    }
    return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(SCREEN_WIDTH/3.0, 49+SYS_TabBarFloatHeight);
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"Selected item at index: %ld", (long)indexPath.item);
    if( [UserInfoModel isLogin] ){
        self.selectIndex = indexPath.row;
        [self.collectionView reloadData];
        [self.pageViewController setViewControllers:@[self.arryViewControllers[indexPath.row]] direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
    }else{
        LoginViewController *vc = [[LoginViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}


#pragma mark - UIPageViewControllerDataSource

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController {
    NSUInteger index = [self.arryViewControllers indexOfObject:viewController];
    if (index == 0) {
        return nil;
    }
    return self.arryViewControllers[index - 1];
}

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController {
    NSUInteger index = [self.arryViewControllers indexOfObject:viewController];
    if (index == self.arryViewControllers.count - 1) {
        return nil;
    }
    return self.arryViewControllers[index + 1];
}



- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray<UIViewController *> *)previousViewControllers transitionCompleted:(BOOL)completed {
    if (completed) {
        UIViewController *currentViewController = self.arryViewControllers[[self.arryViewControllers indexOfObject:pageViewController.viewControllers[0]]];
        //        NSUInteger index = [self.arryViewControllers indexOfObject:currentViewController];
        //        self.pageControl.currentPage = index;
    }
}

- (void)requestCityList{
    
    [HomeRequest requestCityListSuccess:^(NSURLSessionDataTask *task, id response) {
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
}


/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
